package com.itheima.mongo.service.impl;

import com.itheima.mongo.pojo.ApComment;
import com.itheima.mongo.repository.ApCommentRepository;
import com.itheima.mongo.service.ApCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class ApCommentServiceImpl implements ApCommentService {

    @Autowired
    ApCommentRepository apCommentRepository;

    @Override
    public void saveComment(ApComment comment) {
        apCommentRepository.save(comment);
    }

    @Override
    public void deleteCommentById(String id) {
        apCommentRepository.deleteById(id);
    }

    @Override
    public void updateComment(ApComment comment) {
        apCommentRepository.save(comment);
    }

    @Override
    public List<ApComment> findCommentList() {
        List<ApComment> list = apCommentRepository.findAll();
        return list;
    }

    @Override
    public ApComment findCommentById(String id) {
        // JDK 8 新特性 非空判断
        Optional<ApComment> optional = apCommentRepository.findById(id);
        if (optional.isPresent()) {
            ApComment comment = optional.get();
            return comment;
        }

        return null;
    }

    /**
     * 根据条件查询带分页
     * @param address
     * @return
     */
    @Override
    public Page<ApComment> findByAddress(String address, Integer page, Integer size) {

        Pageable pageable = PageRequest.of(page-1, size);

        Page<ApComment> commentPage = apCommentRepository.findByAddress(address, pageable);

        return commentPage;
    }

    /**
     * 分页条件查询
     * @param address
     * @param likes
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<ApComment> findByAddressAndLikesGreaterThan(String address, Integer likes, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page-1, size);

        Page<ApComment> commentPage = apCommentRepository.findByAddressAndLikesGreaterThan(address, likes, pageable);

        return commentPage;
    }

    /**
     * 条件查询
     * @param address
     * @return
     */
    @Override
    public List<ApComment> findCommentListByAddress(String address) {
        ApComment comment = new ApComment();
        comment.setAddress(address);

        List<ApComment> commentList = apCommentRepository.findAll(Example.of(comment));
        return commentList;
    }
}
